<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\User;

class Zpackets extends \Service\Common\BaseModel
{
    protected $name = 'red_packets';

    //转换记录
    public function zpacketsList($uid, $page_num = 1, $page_size = 5)
    {
        $where = [
            'uid' => $uid,
            'type'=> 1
        ];
        $list = (array)$this->where($where)->order('id desc')->page($page_num, $page_size)->select();
        
        $count = $this->where($where)->count();
        return [
            $list,
            $page_count = $count,
            $page_total = ceil($count / $page_size),
            $total_zpackets = get_decimal($this->where($where)->sum('money')),
           
        ];
    }

    //转换提交
    public function zpacketsSubmit($data, $login_info)
    {
        //验证支付密码
        OE('user')->checkpaypassword($login_info['uid'], $data['pay_password']);

        //金额验证
	    $num = 100;
	 
        if ($data['money'] < $num || floor($data['money']) != $data['money'] || $data['money'] % $num !== 0 ) {
        	throw new \Exception("转换金额最少是".$num."的整数倍");
        }
        if (!($data['money'] && $login_info['red_packets'] >= $data['money'])) {
            throw new \Exception("余额不足");
        }

        try {
            $this->startTrans();
            //转换记录
            
             $insert_id = $this->add([
            		'uid'=>$login_info['uid'],
            		'type'=>1,
            		'money'=>-$data['money'],
            		'create_time'=>date('Y-m-d H:i:s')
            		]);
            if (!$insert_id) {
                throw new \Exception("转换记录插入失败");
            }
            $balance = $login_info['balance'] + $data['money'];
            $update = M('user')->where(['uid'=>$login_info['uid']])
					            ->save([
					            		'red_packets'=> ['exp','red_packets-'.$data['money']],
					            		'balance'=> $balance
					            		]);
            if ($update === false) {
            	throw new \Exception("转换失败");
            }
            
            //资金记录
            $moneylogid = M('money_log')->add([
            		'uid'=>$login_info['uid'],
            		'type'=>11,
            		'type_id'=>0,
            		'change_money'=>$data['money'],
            		'old_balance'=>$login_info['balance'],
            		'new_balance'=>$balance,
            		'create_time'=>date('Y-m-d H:i:s')
            		]);
            if (!$moneylogid) {
            	throw new \Exception("资金记录添加失败");
            }
            
            //OE('user')->transfer($login_info['uid'], $user['uid'], $data['money'], $insert_id);
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
    }


}